package com.cah.project.core.dict.handler;

import cn.hutool.cache.CacheUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cah.project.core.dict.domain.vo.DictDataOptions;
import com.cah.project.core.dict.handler.business.IBusinessDictHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 功能描述: 字典加载抽象类 <br/>
 */
@Component
public class BusinessDictHandler extends AbstractDictHandler {

    @Autowired
    private DictHandlerAware dictHandlerAware;

    public BusinessDictHandler() {
        cacheData = CacheUtil.newLFUCache(10000);
    }

    @Override
    public List<DictDataOptions> getDictDataOptions(String typeCode) {
        List<DictDataOptions> dictDataOptions = cacheData.get(typeCode);
        if(CollUtil.isEmpty(dictDataOptions)) {
            IBusinessDictHandler handler = dictHandlerAware.getHandlerMap().get(typeCode);
            if(ObjectUtil.isNotNull(handler)) {
                List<DictDataOptions> dictDataList = handler.getDictDataList();
                put(typeCode, dictDataList);
            } else {
                return ListUtil.empty();
            }
        }
        return cacheData.get(typeCode);
    }

    @Override
    public void loadDictCache() {
        // 查找IBusinessDictHandler的所有实现
        Set<Map.Entry<String, IBusinessDictHandler>> entries = dictHandlerAware.getHandlerMap().entrySet();
        // 循环添加
        for(Map.Entry<String, IBusinessDictHandler> entry : entries) {
            addDictType(entry.getKey(), entry.getValue().typeName());
            put(entry.getKey(), entry.getValue().getDictDataList());
        }
    }

    @Override
    public void reloadDictCache(String typeCode) {
        remove(typeCode);
        IBusinessDictHandler handler = dictHandlerAware.getHandlerMap().get(typeCode);
        if(ObjectUtil.isNotNull(handler)) {
            List<DictDataOptions> dictDataList = handler.getDictDataList();
            if(CollUtil.isNotEmpty(dictDataList)) {
                put(typeCode, dictDataList);
            }
        }
    }

}
